// import __config from "../config/env";

const request = (url, method, data, showLoading, requestTaskKey, ctx) => {
  // let _url = __config.basePath + url;
  return new Promise((resolve, reject) => {
    console.log(ctx, ctx.timer, "[--this");
    // const timer = getApp().globalData.timer;
    ctx.timer && clearTimeout(ctx.timer);
    ctx.timer = setTimeout(() => {
      if (showLoading) {
        wx.showLoading({
          title: "加载中",
        });
      }
      // 判断是否取消请求任务 globalData
      // if (getApp().globalData.requestTasks[requestTaskKey]) {
      //   getApp().globalData.requestTasks[requestTaskKey].abort()
      // }
      const requestGetDataTask = wx.request({
        // url: _url,
        url: `https://ssny.hebsbs.com/${url}`,
        method: method,
        data: data,
        header: {
          "Content-Type":
            method == "post"
              ? "application/x-www-form-urlencoded"
              : "application/json",
          "app-id": wx.getAccountInfoSync().miniProgram.appId,
          "third-session":
            getApp().globalData.thirdSession != null
              ? getApp().globalData.thirdSession
              : "",
        },
        success(res) {
          if (res.statusCode == 200) {
            if (res.data.code == 60001) {
              //session过期，则清除过期session，并重新加载当前页
              getApp().globalData.thirdSession = null;
              wx.reLaunch({
                url: getApp().getCurrentPageUrlWithArgs(),
              });
            } else if (res.data.code == 60002) {
              //token过期，登录过期 请重新登录
              wx.showModal({
                title: "提示",
                content: "登录验证过期，请重新登录",
                showCancel: false,
                success(res) {
                  if (res.confirm) {
                    //wx.exitMiniProgram();
                    wx.showModal({
                      title: "是否未设置用户信息",
                      content: "未设置用户信息导致验证过期，请完善",
                      confirmText: "去完善",
                      cancelText: "重新登录",
                      success(res) {
                        if (res.confirm) {
                          wx.navigateTo({
                            url: "/pages/userinfo/userinfo",
                          });
                        } else if (res.cancel) {
                          wx.exitMiniProgram();
                        }
                      },
                    });
                  }
                },
              });
              reject(res.data.msg);
            } else if (res.data.code == 60000) {
              wx.showModal({
                title: "提示",
                content: "系统错误，请稍候再试",
                success(res) {},
              });
              reject(res.data.msg);
              //没有手机号码则跳转到用户信息页面
            } else if (res.data.code == 60006) {
              wx.showModal({
                title: "提示",
                content: "请先完善个人信息",
                showCancel: false,
                complete(res) {
                  wx.navigateTo({
                    url: "/pages/userinfo/userinfo",
                  });
                },
              });

              //这里可以不用reject
              //reject(res.data.msg)
            } else {
              resolve(res.data);
            }
          } else if (res.statusCode == 404) {
            wx.showModal({
              title: "提示",
              content: "接口请求出错，请检查手机网络",
              success(res) {},
            });
            reject();
          }
          // else if (res.statusCode == 60006) {
          //   console.log(res)
          //   wx.showModal({
          //     title: '提示',
          //     content: res.errMsg + ':' + res.data.message + ':' + res.data.msg,
          //     complete(res) {
          //       wx.navigateTo({
          //         url: '/pages/userinfo/userinfo',
          //       })
          //     }
          //   })
          //   reject()
          // }else if (res.data.code != 200) {
          //   console.log(res.data)
          //   wx.showModal({
          //     title: '提示',
          //     content: res.data.msg ? res.data.msg : '没有数据' + '',
          //     success() {

          //     },
          //     complete(){
          //       if(res.data.code == 60001){
          //         //session过期，则清除过期session，并重新加载当前页
          //         getApp().globalData.thirdSession = null
          //         wx.reLaunch({
          //           url: getApp().getCurrentPageUrlWithArgs()
          //         })
          //       }
          //     }
          //   })
          //   reject(res.data.msg)
          // }
          else {
            console.log(res);
            wx.showModal({
              title: "提示",
              content:
                res.errMsg +
                ":" +
                res.data.message +
                ":" +
                res.data.msg +
                ":" +
                res.statusCode,
              success(res) {},
            });
            reject();
          }
        },
        fail(error) {
          console.log(error);

          if (error.errMsg == "request:fail abort") {
            //如果报这个错误则不作Modal显示
          } else {
            wx.showModal({
              title: "提示",
              content: "接口请求出错：" + error.errMsg,
              success(res) {},
            });
          }

          reject(error);
        },
        complete(res) {
          wx.hideLoading();
        },
      });

      // getApp().globalData.requestTasks[requestTaskKey] = requestGetDataTask;
    }, 500);
  });
};

module.exports = {
  request,
  login: (ctx, data) => {
    //小程序登录接口
    return request("weixin/api/ma/wxuser/login", "post", data, false, "login", ctx);
  },
  wxUserSave: (data) => {
    //微信用户新增
    return request("weixin/api/ma/wxuser", "post", data, true, "wxUserSave");
  },

  getOrderNum: (data) => {
    //加油  初始化订单号
    return request("jiayou/generateOrderNo", "get", data, false, "getOrderNum");
  },
  getCouponPrice: (data) => {
    //加油  获取折扣价格
    return request(
      "jiayou/getFinalPrice",
      "get",
      data,
      false,
      "getCouponPrice"
    );
  },
  getPrePay: (data) => {
    //加油 支付接口   生成预支付订单
    return request("jiayou/pay", "get", data, true, "getPrePay");
  },
  getPayResult: (data) => {
    //加油 获取支付结果  支付成功后查询支付结果接口
    return request("jiayou/queryOrder", "get", data, false, "getPayResult");
  },
  getClosePayOrder: (data) => {
    //加油  关闭订单 取消支付后关闭订单
    return request("jiayou/closeOrder", "get", data, true, "getClosePayOrder");
  },

  //记录  获取openID
  getSubOpenidData: (data) => {
    return request(
      "orderCreate/getOpenId",
      "get",
      data,
      false,
      "getSubOpenidData"
    );
  },
  //记录  获取记录列表数据
  getPayRecordListData: (data) => {
    return request(
      "orderCreate/list",
      "get",
      data,
      true,
      "getPayRecordListData"
    );
  },

  //充值   获取充值余额
  getChongZhiYuEData: (data) => {
    return request("balance/list", "get", data, false, "getChongZhiYuEData");
  },
  //充值   获取充值列表
  getChongZhiListData: (data) => {
    return request("balance/list", "get", data, true, "getChongZhiListData");
  },

  //会员卡支付
  getVipPay: (data) => {
    return request("jiayou/pay", "get", data, false, "getVipPay");
  },
  //获取手机号  废除，改为云函数调用
  getPhoneNumData: (data) => {
    return request("", "get", data, false, "getPhoneNumData");
  },
  //提交个人信息数据
  postUserInfoData: (data) => {
    return request(
      "weixin/api/ma/wxuser/saveWxUser",
      "post",
      data,
      false,
      "postUserInfoData"
    );
  },

  //测试  创建卡券
  getCreateCard: (data) => {
    return request("card/create", "post", data, false);
  },
  //获取优惠券列表
  getCouponListData: (data) => {
    return request("yhqsyMobi/list", "get", data, true, "getCouponListData");
  },
  //获取优惠券列表  首页频繁获取
  getCouponListLotChangData: (data) => {
    return request(
      "yhqsyMobi/list",
      "get",
      data,
      false,
      "getCouponListLotChangData"
    );
  },
  //支付成功后领取优惠券
  getCouponLingData: (data) => {
    return request("yhqsyMobi/getYhq", "get", data, false, "getCouponLingData");
  },

  //订单记录列表头部信息
  getPayListHeaderData: (data) => {
    return request(
      "orderCreate/userStatistics",
      "get",
      data,
      false,
      "getPayListHeaderData"
    );
  },
  //修改支付密码
  changePayPass: (data) => {
    return request(
      "weixin/api/ma/wxuser/updatePassword",
      "post",
      data,
      true,
      "changePayPass"
    );
  },

  //退款
  payMoneyBackUrl: (data) => {
    return request("jiayou/moneyback", "get", data, true, "payMoneyBackUrl");
  },
};
